<template>
  <a-spin :spinning="loading">
    <a-select
      style="width: 100%"
      :dropdownMatchSelectWidth="false"
      :showSearch="true"
      :filter-option="false"
      :maxTagCount="selectPagination.pageSize"
      v-model="selectedValue"
      :disabled="disabled"
      :placeholder="placeholder"
      @search="handleSearch"
      @popupScroll="popupScroll"
      @change="handleChange"
      @blur="handleBlur"
      :notFoundContent="loading ? '加载中' : '无匹配数据'"
    >
      <a-select-option v-for="item in materialData" :key="item.id" :value="item.id">
        <span v-for="(i, index) in materialField" :key="index">
          {{ item[i] }}
          <a-divider type="vertical" style="background-color: #0c8fcf" />
        </span>
      </a-select-option>
    </a-select>
  </a-spin>
</template>

<script>
import debounce from 'lodash/debounce'
import { getAction } from '@api/manage'

export default {
  name: 'HfMaterialSearchSelectTag',
  props: {
    disabled: Boolean,
    value: [String, Number],
    placeholder: {
      type: String,
      default: '请选择',
      required: false
    },
    dataUrl: {
      type: String,
      default: '/material/hfMaterial/queryByMaterialCodeOrName',
      required: false
    },
    materialField: {
      type: Array,
      default: () => ['materialCode', 'materialName', 'sap']
    },
    extraParam: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    this.loadData = debounce(this.loadData, 1200) //消抖
    this.lastLoad = 0
    return {
      loading: false,
      selectedValue: [],
      previousValue: [],
      materialData: [],
      selectPagination: {
        page: 1,
        pageSize: 10
      }
    }
  },
  created() {
    // this.loadData(1)
  },
  watch: {
    dataUrl: {
      handler() {
        this.loadData(1)
      }
    },
    value: {
      immediate: true,
      handler(val) {
        this.selectedValue = val
      }
    }
  },
  beforeDestroy() {
    // 清空数据
    // this.materialData = []
  },
  methods: {
    handleBlur() {
      console.log('失去焦点')
    },
    loadData(arg) {
      // 添加加载状态
      this.loading = true

      let param = {
        pageNo: this.selectPagination.page,
        pageSize: this.selectPagination.pageSize,
        ...this.extraParam
      }

      // 优化搜索逻辑
      if (arg !== 1) {
        param = {
          ...param,
          materialCode: arg,
          materialName: arg
        }
      }
      getAction(this.dataUrl, param)
        .then(res => {
          if (res.success) {
            const data = res.result.records
            if (this.dataUrl === '/material/hfMaterial/queryByMaterialCodeOrName') {
              data.forEach(item => {
                item.materialId = item.id
              })
            }
            // 添加数据去重
            const newData =
              this.selectPagination.page === 1
                ? data
                : data.filter(item => !this.materialData.some(exist => exist.id === item.id))
            this.materialData = this.selectPagination.page === 1 ? data : [...this.materialData, ...newData]
          }
        })
        .catch(error => {
          console.error('加载数据失败:', error)
        })
        .finally(() => {
          this.loading = false
          if (arg === 1) {
            this.hasLoaded = true // 标记已加载初始数据
          }
        })
    },
    popupScroll({ target: { scrollTop, scrollHeight, clientHeight } }) {
      // 添加防抖和加载锁，避免重复请求
      if (!this.loading && scrollHeight - scrollTop <= clientHeight) {
        this.selectPagination.page++
        this.loadData(this.selectedValue)
      }
    },
    handleSearch(value) {
      // 添加搜索防抖
      this.materialData = []
      console.log('search加载')
      this.loadData(value)
      this.selectedValue = value
    },
    handleChange(value) {
      this.selectedValue = value
      this.callback()
    },
    // 传递值给父组件
    callback() {
      let materialData = this.materialData.find(item => item.id === this.selectedValue)
      this.$emit('change', this.selectedValue, materialData)
      console.log('record', materialData)
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped></style>
